{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# United States - Crime Rates - 1960 - 2014"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Introduction:\n",
    "\n",
    "This time you will create a data \n",
    "\n",
    "Special thanks to: https://github.com/justmarkham for sharing the dataset and materials.\n",
    "\n",
    "### Step 1. Import the necessary libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3. Assign it to a variable called crime."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "read_csv() got an unexpected keyword argument 'paras_date'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m--------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m        Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-6-133eaf7fd22e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0murl\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mcrime\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mpd\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mread_csv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0murl\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mparas_date\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      3\u001b[0m \u001b[0mcrime\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mhead\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mTypeError\u001b[0m: read_csv() got an unexpected keyword argument 'paras_date'"
     ]
    }
   ],
   "source": [
    "url = \"https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv\"\n",
    "crime = pd.read_csv(url, paras_date=[[0]])\n",
    "crime.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function read_csv in module pandas.io.parsers:\n",
      "\n",
      "read_csv(filepath_or_buffer: Union[str, pathlib.Path, IO[~AnyStr]], sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal: str = '.', lineterminator=None, quotechar='\"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)\n",
      "    Read a comma-separated values (csv) file into DataFrame.\n",
      "    \n",
      "    Also supports optionally iterating or breaking of the file\n",
      "    into chunks.\n",
      "    \n",
      "    Additional help can be found in the online docs for\n",
      "    `IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.\n",
      "    \n",
      "    Parameters\n",
      "    ----------\n",
      "    filepath_or_buffer : str, path object or file-like object\n",
      "        Any valid string path is acceptable. The string could be a URL. Valid\n",
      "        URL schemes include http, ftp, s3, gs, and file. For file URLs, a host is\n",
      "        expected. A local file could be: file://localhost/path/to/table.csv.\n",
      "    \n",
      "        If you want to pass in a path object, pandas accepts any ``os.PathLike``.\n",
      "    \n",
      "        By file-like object, we refer to objects with a ``read()`` method, such as\n",
      "        a file handler (e.g. via builtin ``open`` function) or ``StringIO``.\n",
      "    sep : str, default ','\n",
      "        Delimiter to use. If sep is None, the C engine cannot automatically detect\n",
      "        the separator, but the Python parsing engine can, meaning the latter will\n",
      "        be used and automatically detect the separator by Python's builtin sniffer\n",
      "        tool, ``csv.Sniffer``. In addition, separators longer than 1 character and\n",
      "        different from ``'\\s+'`` will be interpreted as regular expressions and\n",
      "        will also force the use of the Python parsing engine. Note that regex\n",
      "        delimiters are prone to ignoring quoted data. Regex example: ``'\\r\\t'``.\n",
      "    delimiter : str, default ``None``\n",
      "        Alias for sep.\n",
      "    header : int, list of int, default 'infer'\n",
      "        Row number(s) to use as the column names, and the start of the\n",
      "        data.  Default behavior is to infer the column names: if no names\n",
      "        are passed the behavior is identical to ``header=0`` and column\n",
      "        names are inferred from the first line of the file, if column\n",
      "        names are passed explicitly then the behavior is identical to\n",
      "        ``header=None``. Explicitly pass ``header=0`` to be able to\n",
      "        replace existing names. The header can be a list of integers that\n",
      "        specify row locations for a multi-index on the columns\n",
      "        e.g. [0,1,3]. Intervening rows that are not specified will be\n",
      "        skipped (e.g. 2 in this example is skipped). Note that this\n",
      "        parameter ignores commented lines and empty lines if\n",
      "        ``skip_blank_lines=True``, so ``header=0`` denotes the first line of\n",
      "        data rather than the first line of the file.\n",
      "    names : array-like, optional\n",
      "        List of column names to use. If the file contains a header row,\n",
      "        then you should explicitly pass ``header=0`` to override the column names.\n",
      "        Duplicates in this list are not allowed.\n",
      "    index_col : int, str, sequence of int / str, or False, default ``None``\n",
      "      Column(s) to use as the row labels of the ``DataFrame``, either given as\n",
      "      string name or column index. If a sequence of int / str is given, a\n",
      "      MultiIndex is used.\n",
      "    \n",
      "      Note: ``index_col=False`` can be used to force pandas to *not* use the first\n",
      "      column as the index, e.g. when you have a malformed file with delimiters at\n",
      "      the end of each line.\n",
      "    usecols : list-like or callable, optional\n",
      "        Return a subset of the columns. If list-like, all elements must either\n",
      "        be positional (i.e. integer indices into the document columns) or strings\n",
      "        that correspond to column names provided either by the user in `names` or\n",
      "        inferred from the document header row(s). For example, a valid list-like\n",
      "        `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.\n",
      "        Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.\n",
      "        To instantiate a DataFrame from ``data`` with element order preserved use\n",
      "        ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns\n",
      "        in ``['foo', 'bar']`` order or\n",
      "        ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``\n",
      "        for ``['bar', 'foo']`` order.\n",
      "    \n",
      "        If callable, the callable function will be evaluated against the column\n",
      "        names, returning names where the callable function evaluates to True. An\n",
      "        example of a valid callable argument would be ``lambda x: x.upper() in\n",
      "        ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster\n",
      "        parsing time and lower memory usage.\n",
      "    squeeze : bool, default False\n",
      "        If the parsed data only contains one column then return a Series.\n",
      "    prefix : str, optional\n",
      "        Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...\n",
      "    mangle_dupe_cols : bool, default True\n",
      "        Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than\n",
      "        'X'...'X'. Passing in False will cause data to be overwritten if there\n",
      "        are duplicate names in the columns.\n",
      "    dtype : Type name or dict of column -> type, optional\n",
      "        Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32,\n",
      "        'c': 'Int64'}\n",
      "        Use `str` or `object` together with suitable `na_values` settings\n",
      "        to preserve and not interpret dtype.\n",
      "        If converters are specified, they will be applied INSTEAD\n",
      "        of dtype conversion.\n",
      "    engine : {'c', 'python'}, optional\n",
      "        Parser engine to use. The C engine is faster while the python engine is\n",
      "        currently more feature-complete.\n",
      "    converters : dict, optional\n",
      "        Dict of functions for converting values in certain columns. Keys can either\n",
      "        be integers or column labels.\n",
      "    true_values : list, optional\n",
      "        Values to consider as True.\n",
      "    false_values : list, optional\n",
      "        Values to consider as False.\n",
      "    skipinitialspace : bool, default False\n",
      "        Skip spaces after delimiter.\n",
      "    skiprows : list-like, int or callable, optional\n",
      "        Line numbers to skip (0-indexed) or number of lines to skip (int)\n",
      "        at the start of the file.\n",
      "    \n",
      "        If callable, the callable function will be evaluated against the row\n",
      "        indices, returning True if the row should be skipped and False otherwise.\n",
      "        An example of a valid callable argument would be ``lambda x: x in [0, 2]``.\n",
      "    skipfooter : int, default 0\n",
      "        Number of lines at bottom of file to skip (Unsupported with engine='c').\n",
      "    nrows : int, optional\n",
      "        Number of rows of file to read. Useful for reading pieces of large files.\n",
      "    na_values : scalar, str, list-like, or dict, optional\n",
      "        Additional strings to recognize as NA/NaN. If dict passed, specific\n",
      "        per-column NA values.  By default the following values are interpreted as\n",
      "        NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',\n",
      "        '1.#IND', '1.#QNAN', '<NA>', 'N/A', 'NA', 'NULL', 'NaN', 'n/a',\n",
      "        'nan', 'null'.\n",
      "    keep_default_na : bool, default True\n",
      "        Whether or not to include the default NaN values when parsing the data.\n",
      "        Depending on whether `na_values` is passed in, the behavior is as follows:\n",
      "    \n",
      "        * If `keep_default_na` is True, and `na_values` are specified, `na_values`\n",
      "          is appended to the default NaN values used for parsing.\n",
      "        * If `keep_default_na` is True, and `na_values` are not specified, only\n",
      "          the default NaN values are used for parsing.\n",
      "        * If `keep_default_na` is False, and `na_values` are specified, only\n",
      "          the NaN values specified `na_values` are used for parsing.\n",
      "        * If `keep_default_na` is False, and `na_values` are not specified, no\n",
      "          strings will be parsed as NaN.\n",
      "    \n",
      "        Note that if `na_filter` is passed in as False, the `keep_default_na` and\n",
      "        `na_values` parameters will be ignored.\n",
      "    na_filter : bool, default True\n",
      "        Detect missing value markers (empty strings and the value of na_values). In\n",
      "        data without any NAs, passing na_filter=False can improve the performance\n",
      "        of reading a large file.\n",
      "    verbose : bool, default False\n",
      "        Indicate number of NA values placed in non-numeric columns.\n",
      "    skip_blank_lines : bool, default True\n",
      "        If True, skip over blank lines rather than interpreting as NaN values.\n",
      "    parse_dates : bool or list of int or names or list of lists or dict, default False\n",
      "        The behavior is as follows:\n",
      "    \n",
      "        * boolean. If True -> try parsing the index.\n",
      "        * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3\n",
      "          each as a separate date column.\n",
      "        * list of lists. e.g.  If [[1, 3]] -> combine columns 1 and 3 and parse as\n",
      "          a single date column.\n",
      "        * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call\n",
      "          result 'foo'\n",
      "    \n",
      "        If a column or index cannot be represented as an array of datetimes,\n",
      "        say because of an unparseable value or a mixture of timezones, the column\n",
      "        or index will be returned unaltered as an object data type. For\n",
      "        non-standard datetime parsing, use ``pd.to_datetime`` after\n",
      "        ``pd.read_csv``. To parse an index or column with a mixture of timezones,\n",
      "        specify ``date_parser`` to be a partially-applied\n",
      "        :func:`pandas.to_datetime` with ``utc=True``. See\n",
      "        :ref:`io.csv.mixed_timezones` for more.\n",
      "    \n",
      "        Note: A fast-path exists for iso8601-formatted dates.\n",
      "    infer_datetime_format : bool, default False\n",
      "        If True and `parse_dates` is enabled, pandas will attempt to infer the\n",
      "        format of the datetime strings in the columns, and if it can be inferred,\n",
      "        switch to a faster method of parsing them. In some cases this can increase\n",
      "        the parsing speed by 5-10x.\n",
      "    keep_date_col : bool, default False\n",
      "        If True and `parse_dates` specifies combining multiple columns then\n",
      "        keep the original columns.\n",
      "    date_parser : function, optional\n",
      "        Function to use for converting a sequence of string columns to an array of\n",
      "        datetime instances. The default uses ``dateutil.parser.parser`` to do the\n",
      "        conversion. Pandas will try to call `date_parser` in three different ways,\n",
      "        advancing to the next if an exception occurs: 1) Pass one or more arrays\n",
      "        (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the\n",
      "        string values from the columns defined by `parse_dates` into a single array\n",
      "        and pass that; and 3) call `date_parser` once for each row using one or\n",
      "        more strings (corresponding to the columns defined by `parse_dates`) as\n",
      "        arguments.\n",
      "    dayfirst : bool, default False\n",
      "        DD/MM format dates, international and European format.\n",
      "    cache_dates : bool, default True\n",
      "        If True, use a cache of unique, converted dates to apply the datetime\n",
      "        conversion. May produce significant speed-up when parsing duplicate\n",
      "        date strings, especially ones with timezone offsets.\n",
      "    \n",
      "        .. versionadded:: 0.25.0\n",
      "    iterator : bool, default False\n",
      "        Return TextFileReader object for iteration or getting chunks with\n",
      "        ``get_chunk()``.\n",
      "    chunksize : int, optional\n",
      "        Return TextFileReader object for iteration.\n",
      "        See the `IO Tools docs\n",
      "        <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_\n",
      "        for more information on ``iterator`` and ``chunksize``.\n",
      "    compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n",
      "        For on-the-fly decompression of on-disk data. If 'infer' and\n",
      "        `filepath_or_buffer` is path-like, then detect compression from the\n",
      "        following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no\n",
      "        decompression). If using 'zip', the ZIP file must contain only one data\n",
      "        file to be read in. Set to None for no decompression.\n",
      "    thousands : str, optional\n",
      "        Thousands separator.\n",
      "    decimal : str, default '.'\n",
      "        Character to recognize as decimal point (e.g. use ',' for European data).\n",
      "    lineterminator : str (length 1), optional\n",
      "        Character to break file into lines. Only valid with C parser.\n",
      "    quotechar : str (length 1), optional\n",
      "        The character used to denote the start and end of a quoted item. Quoted\n",
      "        items can include the delimiter and it will be ignored.\n",
      "    quoting : int or csv.QUOTE_* instance, default 0\n",
      "        Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of\n",
      "        QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).\n",
      "    doublequote : bool, default ``True``\n",
      "       When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate\n",
      "       whether or not to interpret two consecutive quotechar elements INSIDE a\n",
      "       field as a single ``quotechar`` element.\n",
      "    escapechar : str (length 1), optional\n",
      "        One-character string used to escape other characters.\n",
      "    comment : str, optional\n",
      "        Indicates remainder of line should not be parsed. If found at the beginning\n",
      "        of a line, the line will be ignored altogether. This parameter must be a\n",
      "        single character. Like empty lines (as long as ``skip_blank_lines=True``),\n",
      "        fully commented lines are ignored by the parameter `header` but not by\n",
      "        `skiprows`. For example, if ``comment='#'``, parsing\n",
      "        ``#empty\\na,b,c\\n1,2,3`` with ``header=0`` will result in 'a,b,c' being\n",
      "        treated as the header.\n",
      "    encoding : str, optional\n",
      "        Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python\n",
      "        standard encodings\n",
      "        <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .\n",
      "    dialect : str or csv.Dialect, optional\n",
      "        If provided, this parameter will override values (default or not) for the\n",
      "        following parameters: `delimiter`, `doublequote`, `escapechar`,\n",
      "        `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to\n",
      "        override values, a ParserWarning will be issued. See csv.Dialect\n",
      "        documentation for more details.\n",
      "    error_bad_lines : bool, default True\n",
      "        Lines with too many fields (e.g. a csv line with too many commas) will by\n",
      "        default cause an exception to be raised, and no DataFrame will be returned.\n",
      "        If False, then these \"bad lines\" will dropped from the DataFrame that is\n",
      "        returned.\n",
      "    warn_bad_lines : bool, default True\n",
      "        If error_bad_lines is False, and warn_bad_lines is True, a warning for each\n",
      "        \"bad line\" will be output.\n",
      "    delim_whitespace : bool, default False\n",
      "        Specifies whether or not whitespace (e.g. ``' '`` or ``'    '``) will be\n",
      "        used as the sep. Equivalent to setting ``sep='\\s+'``. If this option\n",
      "        is set to True, nothing should be passed in for the ``delimiter``\n",
      "        parameter.\n",
      "    low_memory : bool, default True\n",
      "        Internally process the file in chunks, resulting in lower memory use\n",
      "        while parsing, but possibly mixed type inference.  To ensure no mixed\n",
      "        types either set False, or specify the type with the `dtype` parameter.\n",
      "        Note that the entire file is read into a single DataFrame regardless,\n",
      "        use the `chunksize` or `iterator` parameter to return the data in chunks.\n",
      "        (Only valid with C parser).\n",
      "    memory_map : bool, default False\n",
      "        If a filepath is provided for `filepath_or_buffer`, map the file object\n",
      "        directly onto memory and access the data directly from there. Using this\n",
      "        option can improve performance because there is no longer any I/O overhead.\n",
      "    float_precision : str, optional\n",
      "        Specifies which converter the C engine should use for floating-point\n",
      "        values. The options are `None` for the ordinary converter,\n",
      "        `high` for the high-precision converter, and `round_trip` for the\n",
      "        round-trip converter.\n",
      "    \n",
      "    Returns\n",
      "    -------\n",
      "    DataFrame or TextParser\n",
      "        A comma-separated values (csv) file is returned as two-dimensional\n",
      "        data structure with labeled axes.\n",
      "    \n",
      "    See Also\n",
      "    --------\n",
      "    DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.\n",
      "    read_csv : Read a comma-separated values (csv) file into DataFrame.\n",
      "    read_fwf : Read a table of fixed-width formatted lines into DataFrame.\n",
      "    \n",
      "    Examples\n",
      "    --------\n",
      "    >>> pd.read_csv('data.csv')  # doctest: +SKIP\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(pd.read_csv)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 4. What is the type of the columns?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 55 entries, 0 to 54\n",
      "Data columns (total 12 columns):\n",
      " #   Column              Non-Null Count  Dtype\n",
      "---  ------              --------------  -----\n",
      " 0   Year                55 non-null     int64\n",
      " 1   Population          55 non-null     int64\n",
      " 2   Total               55 non-null     int64\n",
      " 3   Violent             55 non-null     int64\n",
      " 4   Property            55 non-null     int64\n",
      " 5   Murder              55 non-null     int64\n",
      " 6   Forcible_Rape       55 non-null     int64\n",
      " 7   Robbery             55 non-null     int64\n",
      " 8   Aggravated_assault  55 non-null     int64\n",
      " 9   Burglary            55 non-null     int64\n",
      " 10  Larceny_Theft       55 non-null     int64\n",
      " 11  Vehicle_Theft       55 non-null     int64\n",
      "dtypes: int64(12)\n",
      "memory usage: 5.3 KB\n"
     ]
    }
   ],
   "source": [
    "crime.info()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### Have you noticed that the type of Year is int64. But pandas has a different type to work with Time Series. Let's see it now.\n",
    "\n",
    "### Step 5. Convert the type of the column Year to datetime64"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 55 entries, 0 to 54\n",
      "Data columns (total 12 columns):\n",
      " #   Column              Non-Null Count  Dtype         \n",
      "---  ------              --------------  -----         \n",
      " 0   Year                55 non-null     datetime64[ns]\n",
      " 1   Population          55 non-null     int64         \n",
      " 2   Total               55 non-null     int64         \n",
      " 3   Violent             55 non-null     int64         \n",
      " 4   Property            55 non-null     int64         \n",
      " 5   Murder              55 non-null     int64         \n",
      " 6   Forcible_Rape       55 non-null     int64         \n",
      " 7   Robbery             55 non-null     int64         \n",
      " 8   Aggravated_assault  55 non-null     int64         \n",
      " 9   Burglary            55 non-null     int64         \n",
      " 10  Larceny_Theft       55 non-null     int64         \n",
      " 11  Vehicle_Theft       55 non-null     int64         \n",
      "dtypes: datetime64[ns](1), int64(11)\n",
      "memory usage: 5.3 KB\n"
     ]
    }
   ],
   "source": [
    "# pd.to_datetime(crime)\n",
    "crime.Year = pd.to_datetime(crime.Year, format='%Y')\n",
    "crime.info()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 6. Set the Year column as the index of the dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Population</th>\n",
       "      <th>Total</th>\n",
       "      <th>Violent</th>\n",
       "      <th>Property</th>\n",
       "      <th>Murder</th>\n",
       "      <th>Forcible_Rape</th>\n",
       "      <th>Robbery</th>\n",
       "      <th>Aggravated_assault</th>\n",
       "      <th>Burglary</th>\n",
       "      <th>Larceny_Theft</th>\n",
       "      <th>Vehicle_Theft</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Year</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1960-01-01</th>\n",
       "      <td>179323175</td>\n",
       "      <td>3384200</td>\n",
       "      <td>288460</td>\n",
       "      <td>3095700</td>\n",
       "      <td>9110</td>\n",
       "      <td>17190</td>\n",
       "      <td>107840</td>\n",
       "      <td>154320</td>\n",
       "      <td>912100</td>\n",
       "      <td>1855400</td>\n",
       "      <td>328200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1961-01-01</th>\n",
       "      <td>182992000</td>\n",
       "      <td>3488000</td>\n",
       "      <td>289390</td>\n",
       "      <td>3198600</td>\n",
       "      <td>8740</td>\n",
       "      <td>17220</td>\n",
       "      <td>106670</td>\n",
       "      <td>156760</td>\n",
       "      <td>949600</td>\n",
       "      <td>1913000</td>\n",
       "      <td>336000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1962-01-01</th>\n",
       "      <td>185771000</td>\n",
       "      <td>3752200</td>\n",
       "      <td>301510</td>\n",
       "      <td>3450700</td>\n",
       "      <td>8530</td>\n",
       "      <td>17550</td>\n",
       "      <td>110860</td>\n",
       "      <td>164570</td>\n",
       "      <td>994300</td>\n",
       "      <td>2089600</td>\n",
       "      <td>366800</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1963-01-01</th>\n",
       "      <td>188483000</td>\n",
       "      <td>4109500</td>\n",
       "      <td>316970</td>\n",
       "      <td>3792500</td>\n",
       "      <td>8640</td>\n",
       "      <td>17650</td>\n",
       "      <td>116470</td>\n",
       "      <td>174210</td>\n",
       "      <td>1086400</td>\n",
       "      <td>2297800</td>\n",
       "      <td>408300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1964-01-01</th>\n",
       "      <td>191141000</td>\n",
       "      <td>4564600</td>\n",
       "      <td>364220</td>\n",
       "      <td>4200400</td>\n",
       "      <td>9360</td>\n",
       "      <td>21420</td>\n",
       "      <td>130390</td>\n",
       "      <td>203050</td>\n",
       "      <td>1213200</td>\n",
       "      <td>2514400</td>\n",
       "      <td>472800</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Population    Total  Violent  Property  Murder  Forcible_Rape  \\\n",
       "Year                                                                        \n",
       "1960-01-01   179323175  3384200   288460   3095700    9110          17190   \n",
       "1961-01-01   182992000  3488000   289390   3198600    8740          17220   \n",
       "1962-01-01   185771000  3752200   301510   3450700    8530          17550   \n",
       "1963-01-01   188483000  4109500   316970   3792500    8640          17650   \n",
       "1964-01-01   191141000  4564600   364220   4200400    9360          21420   \n",
       "\n",
       "            Robbery  Aggravated_assault  Burglary  Larceny_Theft  \\\n",
       "Year                                                               \n",
       "1960-01-01   107840              154320    912100        1855400   \n",
       "1961-01-01   106670              156760    949600        1913000   \n",
       "1962-01-01   110860              164570    994300        2089600   \n",
       "1963-01-01   116470              174210   1086400        2297800   \n",
       "1964-01-01   130390              203050   1213200        2514400   \n",
       "\n",
       "            Vehicle_Theft  \n",
       "Year                       \n",
       "1960-01-01         328200  \n",
       "1961-01-01         336000  \n",
       "1962-01-01         366800  \n",
       "1963-01-01         408300  \n",
       "1964-01-01         472800  "
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "crime = crime.set_index('Year', drop = True)\n",
    "crime.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 7. Delete the Total column"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 269,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Population</th>\n",
       "      <th>Violent</th>\n",
       "      <th>Property</th>\n",
       "      <th>Murder</th>\n",
       "      <th>Forcible_Rape</th>\n",
       "      <th>Robbery</th>\n",
       "      <th>Aggravated_assault</th>\n",
       "      <th>Burglary</th>\n",
       "      <th>Larceny_Theft</th>\n",
       "      <th>Vehicle_Theft</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Year</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1960-01-01</th>\n",
       "      <td>179323175</td>\n",
       "      <td>288460</td>\n",
       "      <td>3095700</td>\n",
       "      <td>9110</td>\n",
       "      <td>17190</td>\n",
       "      <td>107840</td>\n",
       "      <td>154320</td>\n",
       "      <td>912100</td>\n",
       "      <td>1855400</td>\n",
       "      <td>328200</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1961-01-01</th>\n",
       "      <td>182992000</td>\n",
       "      <td>289390</td>\n",
       "      <td>3198600</td>\n",
       "      <td>8740</td>\n",
       "      <td>17220</td>\n",
       "      <td>106670</td>\n",
       "      <td>156760</td>\n",
       "      <td>949600</td>\n",
       "      <td>1913000</td>\n",
       "      <td>336000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1962-01-01</th>\n",
       "      <td>185771000</td>\n",
       "      <td>301510</td>\n",
       "      <td>3450700</td>\n",
       "      <td>8530</td>\n",
       "      <td>17550</td>\n",
       "      <td>110860</td>\n",
       "      <td>164570</td>\n",
       "      <td>994300</td>\n",
       "      <td>2089600</td>\n",
       "      <td>366800</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1963-01-01</th>\n",
       "      <td>188483000</td>\n",
       "      <td>316970</td>\n",
       "      <td>3792500</td>\n",
       "      <td>8640</td>\n",
       "      <td>17650</td>\n",
       "      <td>116470</td>\n",
       "      <td>174210</td>\n",
       "      <td>1086400</td>\n",
       "      <td>2297800</td>\n",
       "      <td>408300</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1964-01-01</th>\n",
       "      <td>191141000</td>\n",
       "      <td>364220</td>\n",
       "      <td>4200400</td>\n",
       "      <td>9360</td>\n",
       "      <td>21420</td>\n",
       "      <td>130390</td>\n",
       "      <td>203050</td>\n",
       "      <td>1213200</td>\n",
       "      <td>2514400</td>\n",
       "      <td>472800</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Population  Violent  Property  Murder  Forcible_Rape  Robbery  \\\n",
       "Year                                                                        \n",
       "1960-01-01   179323175   288460   3095700    9110          17190   107840   \n",
       "1961-01-01   182992000   289390   3198600    8740          17220   106670   \n",
       "1962-01-01   185771000   301510   3450700    8530          17550   110860   \n",
       "1963-01-01   188483000   316970   3792500    8640          17650   116470   \n",
       "1964-01-01   191141000   364220   4200400    9360          21420   130390   \n",
       "\n",
       "            Aggravated_assault  Burglary  Larceny_Theft  Vehicle_Theft  \n",
       "Year                                                                    \n",
       "1960-01-01              154320    912100        1855400         328200  \n",
       "1961-01-01              156760    949600        1913000         336000  \n",
       "1962-01-01              164570    994300        2089600         366800  \n",
       "1963-01-01              174210   1086400        2297800         408300  \n",
       "1964-01-01              203050   1213200        2514400         472800  "
      ]
     },
     "execution_count": 269,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del crime['Total']\n",
    "crime.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 8. Group the year by decades and sum the values\n",
    "\n",
    "#### Pay attention to the Population column number, summing this column is a mistake"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 270,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Population</th>\n",
       "      <th>Violent</th>\n",
       "      <th>Property</th>\n",
       "      <th>Murder</th>\n",
       "      <th>Forcible_Rape</th>\n",
       "      <th>Robbery</th>\n",
       "      <th>Aggravated_assault</th>\n",
       "      <th>Burglary</th>\n",
       "      <th>Larceny_Theft</th>\n",
       "      <th>Vehicle_Theft</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1960</th>\n",
       "      <td>201385000</td>\n",
       "      <td>4134930</td>\n",
       "      <td>45160900</td>\n",
       "      <td>106180</td>\n",
       "      <td>236720</td>\n",
       "      <td>1633510</td>\n",
       "      <td>2158520</td>\n",
       "      <td>13321100</td>\n",
       "      <td>26547700</td>\n",
       "      <td>5292100</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1970</th>\n",
       "      <td>220099000</td>\n",
       "      <td>9607930</td>\n",
       "      <td>91383800</td>\n",
       "      <td>192230</td>\n",
       "      <td>554570</td>\n",
       "      <td>4159020</td>\n",
       "      <td>4702120</td>\n",
       "      <td>28486000</td>\n",
       "      <td>53157800</td>\n",
       "      <td>9739900</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1980</th>\n",
       "      <td>248239000</td>\n",
       "      <td>14074328</td>\n",
       "      <td>117048900</td>\n",
       "      <td>206439</td>\n",
       "      <td>865639</td>\n",
       "      <td>5383109</td>\n",
       "      <td>7619130</td>\n",
       "      <td>33073494</td>\n",
       "      <td>72040253</td>\n",
       "      <td>11935411</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1990</th>\n",
       "      <td>272690813</td>\n",
       "      <td>17527048</td>\n",
       "      <td>119053499</td>\n",
       "      <td>211664</td>\n",
       "      <td>998827</td>\n",
       "      <td>5748930</td>\n",
       "      <td>10568963</td>\n",
       "      <td>26750015</td>\n",
       "      <td>77679366</td>\n",
       "      <td>14624418</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2000</th>\n",
       "      <td>307006550</td>\n",
       "      <td>13968056</td>\n",
       "      <td>100944369</td>\n",
       "      <td>163068</td>\n",
       "      <td>922499</td>\n",
       "      <td>4230366</td>\n",
       "      <td>8652124</td>\n",
       "      <td>21565176</td>\n",
       "      <td>67970291</td>\n",
       "      <td>11412834</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2010</th>\n",
       "      <td>318857056</td>\n",
       "      <td>6072017</td>\n",
       "      <td>44095950</td>\n",
       "      <td>72867</td>\n",
       "      <td>421059</td>\n",
       "      <td>1749809</td>\n",
       "      <td>3764142</td>\n",
       "      <td>10125170</td>\n",
       "      <td>30401698</td>\n",
       "      <td>3569080</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      Population   Violent   Property  Murder  Forcible_Rape  Robbery  \\\n",
       "1960   201385000   4134930   45160900  106180         236720  1633510   \n",
       "1970   220099000   9607930   91383800  192230         554570  4159020   \n",
       "1980   248239000  14074328  117048900  206439         865639  5383109   \n",
       "1990   272690813  17527048  119053499  211664         998827  5748930   \n",
       "2000   307006550  13968056  100944369  163068         922499  4230366   \n",
       "2010   318857056   6072017   44095950   72867         421059  1749809   \n",
       "\n",
       "      Aggravated_assault  Burglary  Larceny_Theft  Vehicle_Theft  \n",
       "1960             2158520  13321100       26547700        5292100  \n",
       "1970             4702120  28486000       53157800        9739900  \n",
       "1980             7619130  33073494       72040253       11935411  \n",
       "1990            10568963  26750015       77679366       14624418  \n",
       "2000             8652124  21565176       67970291       11412834  \n",
       "2010             3764142  10125170       30401698        3569080  "
      ]
     },
     "execution_count": 270,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# To learn more about .resample (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html)\n",
    "# To learn more about Offset Aliases (http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases)\n",
    "\n",
    "# Uses resample to sum each decade\n",
    "crimes = crime.resample('10AS').sum()\n",
    "\n",
    "# Uses resample to get the max value only for the \"Population\" column\n",
    "population = crime['Population'].resample('10AS').max()\n",
    "\n",
    "# Updating the \"Population\" column\n",
    "crimes['Population'] = population\n",
    "\n",
    "crimes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 9. What is the most dangerous decade to live in the US?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 276,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Population            2010\n",
       "Violent               1990\n",
       "Property              1990\n",
       "Murder                1990\n",
       "Forcible_Rape         1990\n",
       "Robbery               1990\n",
       "Aggravated_assault    1990\n",
       "Burglary              1980\n",
       "Larceny_Theft         1990\n",
       "Vehicle_Theft         1990\n",
       "dtype: int64"
      ]
     },
     "execution_count": 276,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# apparently the 90s was a pretty dangerous time in the US\n",
    "crime.idxmax(0)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
